package labox.innovation.gameserver.skills;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilderFactory;

import javolution.util.FastList;
import javolution.util.FastMap;
import labox.innovation.config.Config;
import labox.innovation.gameserver.datatables.SkillTable;
import labox.innovation.gameserver.model.ChanceCondition;
import labox.innovation.gameserver.model.L2Skill;
import labox.innovation.gameserver.model.base.Race;
import labox.innovation.gameserver.skills.conditions.*;
import labox.innovation.gameserver.skills.effects.EffectChanceSkillTrigger;
import labox.innovation.gameserver.skills.funcs.AttributeStringSplice;
import labox.innovation.gameserver.skills.funcs.FuncTemplate;
import labox.innovation.gameserver.skills.funcs.Lambda;
import labox.innovation.gameserver.skills.funcs.LambdaCalc;
import labox.innovation.gameserver.skills.funcs.LambdaConst;
import labox.innovation.gameserver.skills.funcs.LambdaStats;
import labox.innovation.gameserver.templates.StatsSet;
import labox.innovation.gameserver.templates.effects.EffectTemplate;
import labox.innovation.gameserver.templates.item.L2ArmorType;
import labox.innovation.gameserver.templates.item.L2Item;
import labox.innovation.gameserver.templates.item.L2Weapon;
import labox.innovation.gameserver.templates.item.L2WeaponType;
import labox.innovation.gameserver.templates.skills.L2EffectType;
import labox.innovation.gameserver.templates.skills.L2SkillType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * @author mkizub
 * 
 *         TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates
 */
abstract class DocumentBase {
	static Logger _log = LoggerFactory.getLogger(DocumentBase.class.getName());

	private File _file;
	protected Map<String, String[]> _tables;

	DocumentBase(File pFile) {
		_file = pFile;
		_tables = new FastMap<String, String[]>();
	}

	Document parse() {
		Document doc;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setValidating(false);
			factory.setIgnoringComments(true);
			doc = factory.newDocumentBuilder().parse(_file);
		} catch (Exception e) {
			_log.error("Error loading file  " + _file, Config.SERVER_ID, e);
			return null;
		}
		try {
			parseDocument(doc);
		} catch (Exception e) {
			// _log.error( "Error in file {} {}",_file, e.getMessage());
			_log.error("Error parse file  " + _file, Config.SERVER_ID, e);
			return null;
		}
		return doc;
	}

	public abstract void parseDocument(Document doc);

	public abstract StatsSet getStatsSet();

	public abstract String getTableValue(String name);

	public abstract String getTableValue(String name, int idx);

	protected void resetTable() {
		_tables = new FastMap<String, String[]>();
	}

	protected void setTable(String name, String[] table) {
		_tables.put(name, table);
	}

	/**
	 * ��Ҫ���� xml��for��ǩ
	 * 
	 * @param n
	 * @param template
	 */
	protected void parseTemplate(Node n, Object template) {
		Condition condition = null;
		n = n.getFirstChild();
		if (n == null)
			return;
		if ("cond".equalsIgnoreCase(n.getNodeName())) {
			condition = parseCondition(n.getFirstChild(), template);
			Node msg = n.getAttributes().getNamedItem("msg");
			Node msgId = n.getAttributes().getNamedItem("msgId");
			if (condition != null && msg != null)
				condition.setMessage(msg.getNodeValue());
			else if (condition != null && msgId != null) {
				condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
				Node addName = n.getAttributes().getNamedItem("addName");
				if (addName != null && Integer.decode(getValue(msgId.getNodeValue(), null)) > 0)
					condition.addName();
			}
			n = n.getNextSibling();
		}

		for (; n != null; n = n.getNextSibling()) {
			if ("add".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "Add", condition);
			else if ("sub".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "Sub", condition);
			else if ("mul".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "Mul", condition);
			else if ("basemul".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "BaseMul", condition);
			else if ("div".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "Div", condition);
			else if ("setVal".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "Set", condition);
			else if ("enchant".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "Enchant", condition);
			else if ("enchanthp".equalsIgnoreCase(n.getNodeName()))
				attachFunc(n, template, "EnchantHp", condition);
			// else if ("skill".equalsIgnoreCase(n.getNodeName())) attachSkill(n, template, condition);
			else if ("effect".equalsIgnoreCase(n.getNodeName())) {
				if (template instanceof EffectTemplate)
					throw new RuntimeException("Nested effects");
				attachEffect(n, template, condition);
			}

		}// end for

	}

	protected void attachFunc(Node n, Object template, String name, Condition attachCond) {
		// ���Ӱ���״̬
		Stats stat = Stats.valueOfXml(n.getAttributes().getNamedItem("stat").getNodeValue());
		String order = n.getAttributes().getNamedItem("order").getNodeValue();

		//
		Lambda lambda = getLambda(n, template);
		int ord = Integer.decode(getValue(order, template));

		// ���㺯��� ����
		// ����˵ ���Ч��������(���Ըı�)������
		Condition applayCond = parseCondition(n.getFirstChild(), template);

		// �����ħ������ �� ���?������ ��Ҫ��ֳ���
		if (stat == Stats.MAGIC_ATTACK_ATTI || stat == Stats.POWER_ATTACK_ATTI) {

			FuncTemplate ft = null;
			FuncTemplate ft1 = null;
			if (stat == Stats.MAGIC_ATTACK_ATTI) {
				ft = new FuncTemplate(attachCond, applayCond, name, Stats.MAX_MAGIC_ATTACK, ord, lambda);
				ft1 = new FuncTemplate(attachCond, applayCond, name, Stats.MIN_MAGIC_ATTACK, ord, lambda);
			} else {
				ft = new FuncTemplate(attachCond, applayCond, name, Stats.MAX_POWER_ATTACK, ord, lambda);
				ft1 = new FuncTemplate(attachCond, applayCond, name, Stats.MIN_POWER_ATTACK, ord, lambda);
			}

			if (template instanceof L2Item) {
				((L2Item) template).attach(ft);
				((L2Item) template).attach(ft1);
				AttributeStringSplice.getInstance().getAttributeString(name, stat, lambda, template);
			}

			else if (template instanceof L2Skill) {
				((L2Skill) template).attach(ft);
				((L2Skill) template).attach(ft1);
			} else if (template instanceof EffectTemplate) {
				((EffectTemplate) template).attach(ft);
				((EffectTemplate) template).attach(ft1);
			}

		} else {

			FuncTemplate ft = new FuncTemplate(attachCond, applayCond, name, stat, ord, lambda);
			if (template instanceof L2Item) {
				((L2Item) template).attach(ft);
				AttributeStringSplice.getInstance().getAttributeString(name, stat, lambda, template);
			} else if (template instanceof L2Skill)
				((L2Skill) template).attach(ft);
			else if (template instanceof EffectTemplate)
				((EffectTemplate) template).attach(ft);

		}

	}

	// ��LambdaCalc ������㺯��
	protected void attachLambdaFunc(Node n, Object template, LambdaCalc calc) {
		String name = n.getNodeName();
		final StringBuilder sb = new StringBuilder(name);
		sb.setCharAt(0, Character.toUpperCase(name.charAt(0)));
		name = sb.toString();
		Lambda lambda = getLambda(n, template);
		FuncTemplate ft = new FuncTemplate(null, null, name, null, calc.funcs.length, lambda);
		calc.addFunc(ft.getFunc(new Env(), calc));
	}

	/**
	 * ������ ���ܵ� Effect ���󶨵� template��
	 * 
	 * @param n
	 * @param template
	 * @param attachCond
	 */
	protected void attachEffect(Node n, Object template, Condition attachCond) {
		NamedNodeMap attrs = n.getAttributes();

		// �����Ч������
		String name = attrs.getNamedItem("name").getNodeValue().intern();

		/**
		 * Keep this values as default ones, DP needs it
		 */
		int time = 1;
		int count = 1;

		if (attrs.getNamedItem("count") != null) {
			count = Integer.decode(getValue(attrs.getNamedItem("count").getNodeValue(), template));
		}

		// ���Ч��ĳ���ʱ��
		// ���û��ָ��Ч�����ʱ�䣬 ��ôʹ�ü��ܵ�buff����ʱ��
		if (attrs.getNamedItem("time") != null) {
			time = Integer.decode(getValue(attrs.getNamedItem("time").getNodeValue(), template));
		}
		// else if (((L2Skill) template).getBuffDuration() > 0)
		// time = ((L2Skill) template).getBuffDuration() / 1000 / count;

		// Ч���Ƿ���Լ���Ч
		boolean self = false;
		if (attrs.getNamedItem("self") != null) {
			if (getValue(attrs.getNamedItem("self").getNodeValue(), template) == "true")
				self = true;
		}

		//
		int icon = -1;
		if (attrs.getNamedItem("effecticonId") != null) {
			// Ч��ͼ��id
			icon = Integer.decode(attrs.getNamedItem("effecticonId").getNodeValue());
			// if (Integer.decode(getValue(attrs.getNamedItem("noicon").getNodeValue(),template)) == 1)
			// icon = false;
		}

		// ��ü��ܵ�lambdaʽ
		// �˺�ֵ��
		Lambda lambda = getLambda(n, template);
		// Ч�������
		// û��Ϊnull
		Condition applayCond = parseCondition(n.getFirstChild(), template);

		// ����ͨ��Ч��
		AbnormalEffect abnormal = AbnormalEffect.NULL;
		if (attrs.getNamedItem("abnormal") != null) {
			String abn = attrs.getNamedItem("abnormal").getNodeValue();
			abnormal = AbnormalEffect.getByName(abn);
		}
		// �����Ч��
		AbnormalEffect special = AbnormalEffect.NULL;
		if (attrs.getNamedItem("special") != null) {
			String spc = attrs.getNamedItem("special").getNodeValue();
			special = AbnormalEffect.getByName(spc);
		}

		// ?????
		float stackOrder = 0;
		String stackType = "none";
		if (attrs.getNamedItem("stackType") != null) {
			stackType = attrs.getNamedItem("stackType").getNodeValue();
		}
		if (attrs.getNamedItem("stackOrder") != null) {
			stackOrder = Float.parseFloat(getValue(attrs.getNamedItem("stackOrder").getNodeValue(), template));
		}
		// ??

		double effectPower = -1;
		if (attrs.getNamedItem("effectPower") != null)
			effectPower = Double.parseDouble(getValue(attrs.getNamedItem("effectPower").getNodeValue(), template));

		//
		L2EffectType type = null; // ���ܵ�����
		if (attrs.getNamedItem("effectType") != null) {
			String typeName = getValue(attrs.getNamedItem("effectType").getNodeValue(), template);

			try {
				type = Enum.valueOf(L2EffectType.class, typeName);
			} catch (Exception e) {
				throw new IllegalArgumentException("Not EffectType found for: " + typeName);
			}
		}
		//

		if (effectPower > -1 && type == null)
			_log.warn("Missing effectType for effect: {}", name);

		EffectTemplate lt;

		// name Ч�������
		final boolean isChanceSkillTrigger = (name == EffectChanceSkillTrigger.class.getName());

		int trigId = 0;
		if (attrs.getNamedItem("triggeredId") != null)
			trigId = Integer.parseInt(getValue(attrs.getNamedItem("triggeredId").getNodeValue(), template));
		else if (isChanceSkillTrigger)
			throw new NoSuchElementException(name + " requires triggerId");

		int trigLvl = 1;
		if (attrs.getNamedItem("triggeredLevel") != null)
			trigLvl = Integer.parseInt(getValue(attrs.getNamedItem("triggeredLevel").getNodeValue(), template));

		// �������Ч��
		String chanceCond = null;
		if (attrs.getNamedItem("chanceType") != null)
			chanceCond = getValue(attrs.getNamedItem("chanceType").getNodeValue(), template);
		else if (isChanceSkillTrigger)
			throw new NoSuchElementException(name + " requires chanceType");

		int activationChance = 0;
		if (attrs.getNamedItem("activationChance") != null)
			activationChance = Integer.parseInt(getValue(attrs.getNamedItem("activationChance").getNodeValue(), template));
		else if (isChanceSkillTrigger)
			throw new NoSuchElementException(name + " requires activationChance");

		String activationElements = null;
		if (attrs.getNamedItem("activationElements") != null)
			activationElements = getValue(attrs.getNamedItem("activationElements").getNodeValue(), template);

		boolean pvpOnly = false;
		if (attrs.getNamedItem("pvpChanceOnly") != null)
			pvpOnly = Boolean.parseBoolean(getValue(attrs.getNamedItem("pvpChanceOnly").getNodeValue(), template));

		// ���Ч������
		ChanceCondition chance = ChanceCondition.parse(chanceCond, activationChance, activationElements, pvpOnly);

		if (chance == null && isChanceSkillTrigger)
			throw new NoSuchElementException("Invalid chance condition: " + chanceCond + " " + activationChance);

		// Ч��ģ��
		// attachCond : ����Ч��������� applayCond : Ч���ͷŵ����� name : ����
		// lambda : Ч����ֵ(�������˺���)
		lt = new EffectTemplate(attachCond, applayCond, name, lambda, count, time, abnormal, special, stackType, stackOrder, icon, effectPower, type, trigId, trigLvl, chance);

		// ����Ч������ֵ.
		parseTemplate(n, lt);

		if (template instanceof L2Item)
			((L2Item) template).attach(lt);
		else if (template instanceof L2Skill) {
			if (self)
				((L2Skill) template).attachSelf(lt);
			else
				((L2Skill) template).attach(lt);
		}

	}

	/**
	 * ��template����� skill���ܡ� template����Ӱ�켼�ܵ��˺�������
	 * 
	 * @param n
	 * @param template
	 * @param attachCond
	 */
	protected void attachSkill(Node n, Object template, Condition attachCond) {
		NamedNodeMap attrs = n.getAttributes();
		int id = 0, lvl = 1;
		if (attrs.getNamedItem("id") != null) {
			id = Integer.decode(getValue(attrs.getNamedItem("id").getNodeValue(), template));
		}
		if (attrs.getNamedItem("lvl") != null) {
			lvl = Integer.decode(getValue(attrs.getNamedItem("lvl").getNodeValue(), template));
		}
		L2Skill skill = SkillTable.getInstance().getInfo(id, lvl);
		if (attrs.getNamedItem("chance") != null) {
			if (template instanceof L2Weapon || template instanceof L2Item) {
				skill.attach(new ConditionGameChance(Integer.decode(getValue(attrs.getNamedItem("chance").getNodeValue(), template))), true);
			} else {
				skill.attach(new ConditionGameChance(Integer.decode(getValue(attrs.getNamedItem("chance").getNodeValue(), template))), false);
			}
		}
		if (template instanceof L2Weapon) {
			if (attrs.getNamedItem("onUse") != null || (attrs.getNamedItem("onCrit") == null && attrs.getNamedItem("onCast") == null))
				((L2Weapon) template).attach(skill); // Attach as skill triggered on use
		} else if (template instanceof L2Item) {
			((L2Item) template).attach(skill); // Attach as skill triggered on use
		}

	}// end attachSkill

	protected Condition parseCondition(Node n, Object template) {
		// ���ڵ㲻�� ELEMENT_NODE �����һ���ֵܽڵ�
		while (n != null && n.getNodeType() != Node.ELEMENT_NODE)
			n = n.getNextSibling();
		if (n == null)
			return null;
		if ("and".equalsIgnoreCase(n.getNodeName()))
			return parseLogicAnd(n, template);
		if ("or".equalsIgnoreCase(n.getNodeName()))
			return parseLogicOr(n, template);
		if ("not".equalsIgnoreCase(n.getNodeName()))
			return parseLogicNot(n, template);
		if ("player".equalsIgnoreCase(n.getNodeName()))
			return parsePlayerCondition(n, template);
		if ("target".equalsIgnoreCase(n.getNodeName()))
			return parseTargetCondition(n, template);
		if ("using".equalsIgnoreCase(n.getNodeName()))
			return parseUsingCondition(n);
		if ("game".equalsIgnoreCase(n.getNodeName()))
			return parseGameCondition(n);
		return null;
	}

	protected Condition parseLogicAnd(Node n, Object template) {
		ConditionLogicAnd cond = new ConditionLogicAnd();
		for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
			if (n.getNodeType() == Node.ELEMENT_NODE)
				cond.add(parseCondition(n, template));
		}
		if (cond.conditions == null || cond.conditions.length == 0) {
			if (_log.isDebugEnabled()) {
				_log.debug("Empty <and> condition in " + _file);
			}
		}

		return cond;
	}

	protected Condition parseLogicOr(Node n, Object template) {
		ConditionLogicOr cond = new ConditionLogicOr();
		for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
			if (n.getNodeType() == Node.ELEMENT_NODE)
				cond.add(parseCondition(n, template));
		}
		if (cond.conditions == null || cond.conditions.length == 0) {
			if (_log.isDebugEnabled()) {
				_log.debug("Empty <or> condition in " + _file);
			}

		}

		return cond;
	}

	protected Condition parseLogicNot(Node n, Object template) {
		for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
			if (n.getNodeType() == Node.ELEMENT_NODE) {
				return new ConditionLogicNot(parseCondition(n, template));
			}
		}

		_log.warn("Empty <not> condition in " + _file, Config.SERVER_ID);
		return null;
	}

	protected Condition parsePlayerCondition(Node n, Object template) {
		Condition cond = null;
		L2Item tempitem = null;
		if (template instanceof L2Item) {
			tempitem = (L2Item) template;
		}

		NamedNodeMap attrs = n.getAttributes();
		for (int i = 0; i < attrs.getLength(); i++) {
			Node a = attrs.item(i);
			if ("race".equalsIgnoreCase(a.getNodeName())) {
				Race race = Race.valueOf(a.getNodeValue());
				cond = joinAnd(cond, new ConditionPlayerRace(race));
			}
			// �ȼ�����
			else if ("level".equalsIgnoreCase(a.getNodeName())) {
				int lvl = Integer.decode(getValue(a.getNodeValue(), template));
				if (tempitem != null) {
					tempitem.setItemCondition().setlvl(lvl);
				}

				cond = joinAnd(cond, new ConditionPlayerLevel(lvl));
			} else if ("hp".equalsIgnoreCase(a.getNodeName())) {
				int hp = Integer.decode(getValue(a.getNodeValue(), null));
				cond = joinAnd(cond, new ConditionPlayerHp(hp));
			} else if ("hprate".equalsIgnoreCase(a.getNodeName())) {
				double rate = Double.parseDouble(getValue(a.getNodeValue(), null));
				cond = joinAnd(cond, new ConditionPlayerHpPercentage(rate));
			} else if ("mp".equalsIgnoreCase(a.getNodeName())) {
				int hp = Integer.decode(getValue(a.getNodeValue(), null));
				cond = joinAnd(cond, new ConditionPlayerMp(hp));
			} else if ("grade".equalsIgnoreCase(a.getNodeName())) {
				int expIndex = Integer.decode(getValue(a.getNodeValue(), template));
				cond = joinAnd(cond, new ConditionPlayerGrade(expIndex));
			} else if ("invSize".equalsIgnoreCase(a.getNodeName())) {
				int size = Integer.decode(getValue(a.getNodeValue(), null));
				cond = joinAnd(cond, new ConditionPlayerInvSize(size));
			} else if ("isClanLeader".equalsIgnoreCase(a.getNodeName())) {
				boolean val = Boolean.valueOf(a.getNodeValue());
				cond = joinAnd(cond, new ConditionPlayerIsClanLeader(val));
			} else if ("pledgeClass".equalsIgnoreCase(a.getNodeName())) {
				// int pledgeClass = Integer.decode(getValue(a.getNodeValue(), null));
				FastList<Integer> array = new FastList<Integer>();
				StringTokenizer st = new StringTokenizer(a.getNodeValue(), ",");
				while (st.hasMoreTokens()) {
					String item = st.nextToken().trim();
					array.add(Integer.decode(getValue(item, null)));
				}

				if (tempitem != null) {
					tempitem.setItemCondition().setPracticeId(array);
				}

				cond = joinAnd(cond, new ConditionPlayerPledgeClass(array));
			} else if ("skill".equalsIgnoreCase(a.getNodeName())) {
				FastList<Integer> array = new FastList<Integer>();
				StringTokenizer st = new StringTokenizer(a.getNodeValue(), ",");
				while (st.hasMoreTokens()) {
					String item = st.nextToken().trim();
					array.add(Integer.decode(getValue(item, null)));
				}
				cond = joinAnd(cond, new ConditionPlayerSkill(array));
			} else if ("sex".equalsIgnoreCase(a.getNodeName())) {
				int sex = Integer.decode(getValue(a.getNodeValue(), null));

				if (tempitem != null) {
					tempitem.setItemCondition().setSex(sex);
				}
				cond = joinAnd(cond, new ConditionPlayerSex(sex));
			} else if ("active_effect_id".equalsIgnoreCase(a.getNodeName())) {
				int effect_id = Integer.decode(getValue(a.getNodeValue(), template));
				cond = joinAnd(cond, new ConditionPlayerActiveEffectId(effect_id));
			} else if ("active_effect_id_lvl".equalsIgnoreCase(a.getNodeName())) {
				String val = getValue(a.getNodeValue(), template);
				int effect_id = Integer.decode(getValue(val.split(",")[0], template));
				int effect_lvl = Integer.decode(getValue(val.split(",")[1], template));
				cond = joinAnd(cond, new ConditionPlayerActiveEffectId(effect_id, effect_lvl));
			} else if ("active_skill_id".equalsIgnoreCase(a.getNodeName())) {
				int skill_id = Integer.decode(getValue(a.getNodeValue(), template));
				cond = joinAnd(cond, new ConditionPlayerActiveSkillId(skill_id));
			} else if ("active_skill_id_lvl".equalsIgnoreCase(a.getNodeName())) {
				String val = getValue(a.getNodeValue(), template);
				int skill_id = Integer.decode(getValue(val.split(",")[0], template));
				int skill_lvl = Integer.decode(getValue(val.split(",")[1], template));
				cond = joinAnd(cond, new ConditionPlayerActiveSkillId(skill_id, skill_lvl));
			}
			// ְҵ����
			else if ("class_id_restriction".equalsIgnoreCase(a.getNodeName())) {
				FastList<Integer> array = new FastList<Integer>();
				StringTokenizer st = new StringTokenizer(a.getNodeValue(), ",");
				while (st.hasMoreTokens()) {
					String item = st.nextToken().trim();
					array.add(Integer.decode(getValue(item, null)));
				}
				if (tempitem != null) {
					tempitem.setItemCondition().setClassId(array);
				}
				cond = joinAnd(cond, new ConditionPlayerClassIdRestriction(array));
			} else if ("instanceid".equalsIgnoreCase(a.getNodeName())) {
				FastList<Integer> array = new FastList<Integer>();
				StringTokenizer st = new StringTokenizer(a.getNodeValue(), ",");
				while (st.hasMoreTokens()) {
					String item = st.nextToken().trim();
					array.add(Integer.decode(getValue(item, null)));
				}
				cond = joinAnd(cond, new ConditionPlayerInstanceId(array));
			}
		}

		if (cond == null) {
			_log.warn("Unrecognized <player> condition in " + _file, Config.SERVER_ID);
		}
		return cond;
	}

	protected Condition parseTargetCondition(Node n, Object template) {
		Condition cond = null;
		NamedNodeMap attrs = n.getAttributes();
		for (int i = 0; i < attrs.getLength(); i++) {
			Node a = attrs.item(i);
			if ("aggro".equalsIgnoreCase(a.getNodeName())) {
				boolean val = Boolean.valueOf(a.getNodeValue());
				cond = joinAnd(cond, new ConditionTargetAggro(val));
			} else if ("level".equalsIgnoreCase(a.getNodeName())) {
				int lvl = Integer.decode(getValue(a.getNodeValue(), template));
				cond = joinAnd(cond, new ConditionTargetLevel(lvl));
			} else if ("class_id_restriction".equalsIgnoreCase(a.getNodeName())) {
				FastList<Integer> array = new FastList<Integer>();
				StringTokenizer st = new StringTokenizer(a.getNodeValue(), ",");
				while (st.hasMoreTokens()) {
					String item = st.nextToken().trim();
					array.add(Integer.decode(getValue(item, null)));
				}
				cond = joinAnd(cond, new ConditionTargetClassIdRestriction(array));
			} else if ("active_effect_id".equalsIgnoreCase(a.getNodeName())) {
				int effect_id = Integer.decode(getValue(a.getNodeValue(), template));
				cond = joinAnd(cond, new ConditionTargetActiveEffectId(effect_id));
			} else if ("active_effect_id_lvl".equalsIgnoreCase(a.getNodeName())) {
				String val = getValue(a.getNodeValue(), template);
				int effect_id = Integer.decode(getValue(val.split(",")[0], template));
				int effect_lvl = Integer.decode(getValue(val.split(",")[1], template));
				cond = joinAnd(cond, new ConditionTargetActiveEffectId(effect_id, effect_lvl));
			} else if ("active_skill_id".equalsIgnoreCase(a.getNodeName())) {
				int skill_id = Integer.decode(getValue(a.getNodeValue(), template));
				cond = joinAnd(cond, new ConditionTargetActiveSkillId(skill_id));
			} else if ("active_skill_id_lvl".equalsIgnoreCase(a.getNodeName())) {
				String val = getValue(a.getNodeValue(), template);
				int skill_id = Integer.decode(getValue(val.split(",")[0], template));
				int skill_lvl = Integer.decode(getValue(val.split(",")[1], template));
				cond = joinAnd(cond, new ConditionTargetActiveSkillId(skill_id, skill_lvl));
			} else if ("abnormal".equalsIgnoreCase(a.getNodeName())) {
				int abnormalId = Integer.decode(getValue(a.getNodeValue(), template));
				cond = joinAnd(cond, new ConditionTargetAbnormal(abnormalId));
			} else if ("mindistance".equalsIgnoreCase(a.getNodeName())) {
				int distance = Integer.decode(getValue(a.getNodeValue(), null));
				cond = joinAnd(cond, new ConditionMinDistance(distance * distance));
			}
			// used for pc race
			else if ("race".equalsIgnoreCase(a.getNodeName())) {
				Race race = Race.valueOf(a.getNodeValue());
				cond = joinAnd(cond, new ConditionTargetRace(race));
			} else if ("using".equalsIgnoreCase(a.getNodeName())) {
				int mask = 0;
				StringTokenizer st = new StringTokenizer(a.getNodeValue(), ",");
				while (st.hasMoreTokens()) {
					String item = st.nextToken().trim();
					for (L2WeaponType wt : L2WeaponType.values()) {
						if (wt.toString().equals(item)) {
							mask |= wt.mask();
							break;
						}
					}
					for (L2ArmorType at : L2ArmorType.values()) {
						if (at.toString().equals(item)) {
							mask |= at.mask();
							break;
						}
					}
				}
				cond = joinAnd(cond, new ConditionTargetUsesWeaponKind(mask));
			} else if ("npcId".equalsIgnoreCase(a.getNodeName())) {
				String values = getValue(a.getNodeValue(), template).trim();
				String[] valuesSplit = values.split(" ");
				cond = joinAnd(cond, new ConditionTargetNpcId(valuesSplit));
			} else if ("npcType".equalsIgnoreCase(a.getNodeName())) {
				String values = getValue(a.getNodeValue(), template).trim();
				String[] valuesSplit = values.split(" ");
				cond = joinAnd(cond, new ConditionTargetNpcType(valuesSplit));
			}
		}
		if (cond == null) {
			_log.warn("Unrecognized <target> condition in " + _file, Config.SERVER_ID);
		}
		return cond;
	}

	protected Condition parseUsingCondition(Node n) {
		Condition cond = null;
		NamedNodeMap attrs = n.getAttributes();
		for (int i = 0; i < attrs.getLength(); i++) {
			Node a = attrs.item(i);

			if ("skill".equalsIgnoreCase(a.getNodeName())) {
				int id = Integer.parseInt(a.getNodeValue());
				cond = joinAnd(cond, new ConditionUsingSkill(id));
			} else if ("slotitem".equalsIgnoreCase(a.getNodeName())) {
				StringTokenizer st = new StringTokenizer(a.getNodeValue(), ";");
				int id = Integer.parseInt(st.nextToken().trim());
				int slot = Integer.parseInt(st.nextToken().trim());
				int enchant = 0;
				if (st.hasMoreTokens())
					enchant = Integer.parseInt(st.nextToken().trim());
				cond = joinAnd(cond, new ConditionSlotItemId(slot, id, enchant));
			} else if ("weaponChange".equalsIgnoreCase(a.getNodeName())) {
				boolean val = Boolean.valueOf(a.getNodeValue());
				cond = joinAnd(cond, new ConditionChangeWeapon(val));
			}
		}
		if (cond == null) {
			_log.warn("Unrecognized <using> condition in " + _file, Config.SERVER_ID);
		}
		return cond;
	}

	protected Condition parseGameCondition(Node n) {
		Condition cond = null;
		NamedNodeMap attrs = n.getAttributes();
		for (int i = 0; i < attrs.getLength(); i++) {
			Node a = attrs.item(i);
			if ("skill".equalsIgnoreCase(a.getNodeName())) {
				boolean val = Boolean.valueOf(a.getNodeValue());
				cond = joinAnd(cond, new ConditionWithSkill(val));
			}
			if ("chance".equalsIgnoreCase(a.getNodeName())) {
				int val = Integer.decode(getValue(a.getNodeValue(), null));
				cond = joinAnd(cond, new ConditionGameChance(val));
			}
		}
		if (cond == null) {
			_log.warn("Unrecognized <game> condition in " + _file, Config.SERVER_ID);
		}
		return cond;
	}

	protected void parseTable(Node n) {
		NamedNodeMap attrs = n.getAttributes();
		String name = attrs.getNamedItem("name").getNodeValue();
		if (name.charAt(0) != '#')
			throw new IllegalArgumentException("Table name must start with #");
		StringTokenizer data = new StringTokenizer(n.getFirstChild().getNodeValue());
		List<String> array = new FastList<String>();
		while (data.hasMoreTokens())
			array.add(data.nextToken());
		String[] res = new String[array.size()];
		int i = 0;
		for (String str : array) {
			res[i++] = str;
		}
		setTable(name, res);
	}

	/**
	 * ����set�ֶ� ����set�ֶ��е� name �� value
	 * 
	 * @param n
	 * @param set
	 * @param level
	 */
	protected void parseBeanSet(Node n, StatsSet set, Integer level) {
		String name = n.getAttributes().getNamedItem("name").getNodeValue().trim();
		String value = n.getAttributes().getNamedItem("val").getNodeValue().trim();
		char ch = value.length() == 0 ? ' ' : value.charAt(0);
		if (ch == '#' || ch == '-' || Character.isDigit(ch))
			set.set(name, String.valueOf(getValue(value, level)));
		else
			set.set(name, value);

	}

	protected Lambda getLambda(Node n, Object template) {
		Stats stat = null;
		if (n.getAttributes().getNamedItem("stat") != null) {
			stat = Stats.valueOfXml(n.getAttributes().getNamedItem("stat").getNodeValue());
		}

		Node nval = n.getAttributes().getNamedItem("val");
		// ���ܵ�Lambdaʽ
		if (nval != null) {
			String val = nval.getNodeValue();
			if (val.charAt(0) == '#') { // table by level
				return new LambdaConst(Double.parseDouble(getTableValue(val)));
			} else if (val.charAt(0) == '$') {
				if (val.equalsIgnoreCase("$item_grade"))
					return new LambdaStats(LambdaStats.StatsType.ITEM_GRADE);

				// �����е� ���Լ��� ��� ��Ӧ��ֵ
				StatsSet set = getStatsSet();
				String field = set.getString(val.substring(1));
				if (field != null) {
					return new LambdaConst(Double.parseDouble(getValue(field, template)));
				}
				// ���û����Ӧ��ֵ ��ô �������ֵ ������
				throw new IllegalArgumentException("Unknown value " + val);
			} else {
				// ����Ǽ��ܣ�����״̬�Ǹ��Ӽ��ܣ� ��ô���յ�ֵΪ���Ӽ��ܵĹ�ϣ��
				if (stat != null && stat == Stats.ADD_SKILL && template instanceof L2Skill) {
					int skid = Integer.parseInt(val);
					double res = SkillTable.getSkillHashCode(skid, ((L2Skill) template).getLevel());
					return new LambdaConst(res);
				} else
					return new LambdaConst(Double.parseDouble(val));
			}

		} // end if (nval != null)
		//

		/* ����ڵ�ǰ�Ľڵ���û�� ����valֵ ��ô�����Ǹ�����ֵ */
		/**
		 * eg: <add order="0x10" stat="dex" val="20"/> ����һ���
		 * 
		 * <add order="0x10" stat="dex"> <val> <add order="0x10" stat="dex" val="20"/> ����2����stat��ûʲô�ô��� <mul order="0x10" stat="dex" val="$item_grade"/> </val> </add>
		 * 
		 * ��2�� add ��val���Ǹ�����ֵLambdaCalc�� ��+ �� x�õ� ���յ�ֵ �� 20 * item_grade; LambdaCalc���ս����� 20 * item_grade
		 */
		LambdaCalc calc = new LambdaCalc();
		n = n.getFirstChild();
		while (n != null && n.getNodeType() != Node.ELEMENT_NODE)
			n = n.getNextSibling();
		if (n == null || !"val".equals(n.getNodeName()))
			throw new IllegalArgumentException("Value not specified");

		for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
			if (n.getNodeType() != Node.ELEMENT_NODE)
				continue;
			attachLambdaFunc(n, template, calc);
		}

		return calc;

	}

	protected String getValue(String value, Object template) {
		// is it a table?
		if (value.charAt(0) == '#') {
			if (template instanceof L2Skill)
				return getTableValue(value);
			else if (template instanceof Integer)
				return getTableValue(value, ((Integer) template).intValue());
			else
				throw new IllegalStateException();
		}
		return value;
	}

	protected Condition joinAnd(Condition cond, Condition c) {
		if (cond == null)
			return c;
		if (cond instanceof ConditionLogicAnd) {
			((ConditionLogicAnd) cond).add(c);
			return cond;
		}
		ConditionLogicAnd and = new ConditionLogicAnd();
		and.add(cond);
		and.add(c);
		return and;
	}
}
